package com.lsmo.android.carfans.app.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lsmo.android.carfans.R;
import com.lsmo.android.common.base.ViewProcessCallBack;
 

public class TabsView extends LinearLayout  implements ViewProcessCallBack{

	public static final String TAG = TabsView.class.getSimpleName();
	
	private ViewPager mPager;//页卡内容
	private ImageView  cursor;// 动画图片
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	private int  screenW ; //屏幕宽度

	private Activity mActivity;
	private TextView [] textArrs ;
	private LinearLayout mTabsItemContentLayout; //tabs子项的容器布局
	private RelativeLayout mTabsCursorContentRLayout ; //存放游标的布局
	private String[] mTabNames ;
	
	private int[] mImageId;
	private   View[]  mViews;
	
	public static final int TABS_STYLE_TEXT_TOP = 1 ;
	public static final int TABS_STYLE_TEXT_BOTTOM = 2 ;
	public static final int TABS_STYLE_IMAGE_TOP = 3 ;
	public static final int TABS_STYLE_IMAGE_BOTTOM = 4 ;
	
	 
	
	public TabsView(Activity activity,int style ,String[] tabNames, View[]  views) {
		// TODO Auto-generated constructor stub
		super(activity);	
		mActivity = activity;
		mTabNames = tabNames;
		mViews = views ;
		currIndex = 0;
		initView(style);
		
		textArrs[currIndex].setTextColor(Color.WHITE);
		
	}
	
	
	public TabsView(Activity activity,int style ,int[] imageId, View[]  views) {
		// TODO Auto-generated constructor stub
		super(activity);	
        
	}
	
	
 
	
	public void initView(int style){
 
 		offset = 0 ;
		textArrs = new TextView[this.mTabNames.length];
		int layoutId  = (style==TABS_STYLE_TEXT_TOP)?R.layout.common_tabs_top_layout:R.layout.common_tabs_bottom_layout ;
		mActivity.getLayoutInflater().inflate(layoutId, this);	
		DisplayMetrics dm = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenW = dm.widthPixels;// 获取分辨率宽度		
		bmpW = screenW / this.mTabNames.length;
		mTabsCursorContentRLayout  =  (RelativeLayout)this.findViewById(R.id.tab_cusor_rlayout);
		mTabsItemContentLayout = (LinearLayout)this.findViewById(R.id.tab_content_layout);
        
		cursor = (ImageView)this.findViewById(R.id.tab_cursor);//游标
//		Matrix matrix = new Matrix();
//		matrix.postTranslate(offset+(screenW/4)*currIndex, 0);
//		cursor.setImageMatrix(matrix);// 设置动画初始位置
        
        mPager = (ViewPager) findViewById(R.id.tab_vPager);//tab显示内容容器
        mPager.setAdapter(new MyPagerAdapter(mViews));
		mPager.setCurrentItem(currIndex);

		mPager.setOnPageChangeListener(new MyOnPageChangeListener());	
        
		
		TextView textView = null ;
		LinearLayout.LayoutParams  lp = 
 			new LinearLayout.LayoutParams( 
 					LinearLayout.LayoutParams.FILL_PARENT	 ,
 					LinearLayout.LayoutParams.FILL_PARENT);
		
		 lp.weight=1;
		int size= getTextSize(mTabNames.length);
        //设置tabs值
        for(int i = 0 ; i<mTabNames.length;i++ ){
        	  textView =  (TextView)mActivity.getLayoutInflater().inflate(R.layout.common_tabs_text_layout, null);
        	  if(mTabNames[i]!=null)
        	  textView.setText(mTabNames[i]);
        	  
        	  
        	  textView.setTextSize(size);
        	  textView.setOnClickListener(new MyOnClickListener(i));
        	  
              mTabsItemContentLayout.addView(textView,lp);
              textArrs[i] =  textView ;    
            
        }
        
	    //设置游标的布局
		RelativeLayout.LayoutParams rLp = 
 			new RelativeLayout.LayoutParams( 
 				 screenW/this.mTabNames.length	 ,
 				RelativeLayout.LayoutParams.FILL_PARENT);
		rLp.setMargins(0, 10, 0, 10);
		mTabsCursorContentRLayout.updateViewLayout(cursor, rLp);
   
        
	}
	
	
	public TabsView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
	//	public List<View> mListViews;
		private int lastInstanceItemIdx =0;
        public  View[] mViewArrs ;
 
        
		public MyPagerAdapter(View[] views/*List<View> mListViews*/) {
			//this.mListViews = mListViews;
			mViewArrs = views ;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mViewArrs[arg1]);
			 
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
 
			return mViewArrs.length;
		}
 
		@Override
		public Object instantiateItem(View arg0, int arg1) {
 
			((ViewPager) arg0).addView(mViewArrs[arg1], 0);
 
			if(lastInstanceItemIdx  == arg1 && lastInstanceItemIdx ==0 ){
				try{
	            	((ViewProcessCallBack)(mViewArrs[arg1])).updateView();
	            }catch(Exception e){
	    			e.printStackTrace();
	    		}
			}
			this.lastInstanceItemIdx = arg1 ;
			return mViewArrs[arg1];
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
		//	LogUtil.v(TAG, "isViewFromObject()----->"); 
	 
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
 
		}

		@Override
		public Parcelable saveState() {
 
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}
	}

	/**
	 * tab点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
			
		}

		
		
		@Override
		public void onClick(View v) {
			 
			mPager.setCurrentItem(index);
			textArrs[index].setTextColor(Color.WHITE);
			 
	   
			
		}
		
		
		
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset*2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量
		int three = one * 3 ;//页卡1 -> 页卡4 偏移量
		
 
		@Override
		public void onPageSelected(int toIdx) {
			try{
				Animation animation = null;
				float fromX = 0 ,toX = 0;
				toX = one*toIdx ;
				fromX = one*currIndex;
				animation = new TranslateAnimation(fromX,toX, 0, 0);
				textArrs[toIdx].setTextColor(Color.WHITE);
			    textArrs[currIndex].setTextColor(Color.BLACK); //还原
				currIndex = toIdx;
				animation.setFillAfter(true);// True:图片停在动画结束位置
				animation.setDuration(300);
				cursor.startAnimation(animation);
				
				((ViewProcessCallBack)(mViews[toIdx])).updateView();
				
			}catch(Exception e){
				e.printStackTrace();
			}

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
 
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		
		
		}
	}
	 
	
	/***
	 * 获取文本大小
	 * @param tabsCount
	 * @return
	 */
	private int getTextSize(int tabsCount){
		int size = 20;
		int defaultTabs = 3;
		if(tabsCount>defaultTabs){
			size = size-(tabsCount-defaultTabs)*3 ;
		}
		
		return size;
	}
	
	//dip转 px	
	public   static int dip2px(Context context, float dipValue){ 
		final float scale = context.getResources().getDisplayMetrics().density;
  	return (int)(dipValue * scale + 0.5f);
   
		} 
//px 转 dip
	public  static int px2dip(Context context, float pxValue){
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int)(pxValue / scale + 0.5f);
		}
    
	/**
	  * 将px值转换为sp值，保证文字大小不变
	  *
	  * @param pxValue
	  * @param fontScale（DisplayMetrics类中属性scaledDensity）
	  * @return
	  */
	 public static int px2sp(Context context,float pxValue) {
		 final float scale = context.getResources().getDisplayMetrics().scaledDensity;
	  return (int) (pxValue / scale + 0.5f);
	 }

	 /**
	  * 将sp值转换为px值，保证文字大小不变
	  *
	  * @param spValue
	  * @param fontScale（DisplayMetrics类中属性scaledDensity）
	  * @return
	  */
	 public static int sp2px(Context context,float spValue) {
		 final float scale = context.getResources().getDisplayMetrics().scaledDensity;
	  return (int) (spValue * scale + 0.5f);
	 }


 


	@Override
	public void updateView() {
		// TODO Auto-generated method stub
		
	}

 
	@Override
	public void processAfterTaskFinish(int code, Object result) {
		// TODO Auto-generated method stub
		
	}
}
